package com.example.music.ui.play;

import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.app.Application;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.Navigation;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.music.App;
import com.example.music.MainActivity;
import com.example.music.R;
import com.example.music.databinding.FragmentMusicBinding;
import com.example.music.databinding.PlayFragmentBinding;
import com.example.music.entity.DataMusic;
import com.example.music.lrc.DefaultLrcBuilder;
import com.example.music.lrc.ILrcViewListener;
import com.example.music.lrc.LrcRow;
import com.example.music.ui.music.MusicViewModel;
import com.example.music.utlis.LogUtil;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class PlayFragment extends Fragment {

    private PlayViewModel mViewModel;
    private PlayFragmentBinding binding;
    //更新歌词的频率，每秒更新一次
    private int mPalyTimerDuration = 500;
    //更新歌词的定时器
    private Timer mTimer;
    //更新歌词的定时任务
    private TimerTask mTask;
    private App application;
    private Object musics1;
    private SimpleDateFormat sdr = new SimpleDateFormat("mm:ss");
    private long time;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        mViewModel = new ViewModelProvider(this).get(PlayViewModel.class);
        binding = PlayFragmentBinding.inflate(inflater, container, false);
        application = (App) getActivity().getApplication();
        Bundle arguments = getArguments();
        DataMusic musics;
        musics1 = arguments.get("musics");
        if(musics1 ==null){
            musics = application.getDataMusic();
        }else {
            musics = (DataMusic) musics1;
        }
        String lyric = musics.getLyric();
        DefaultLrcBuilder builder = new DefaultLrcBuilder();
        List<LrcRow> lrcRows = builder.getLrcRows(lyric);
        binding.lrcView.setLrc(lrcRows);
        time = lrcRows.get(lrcRows.size() - 1).time;
        binding.sbSpeed255.setMax((int) time);
        binding.total.setText(sdr.format(time));
        beginLrcPlay((DataMusic) musics1);
        binding.lrcView.setListener(new ILrcViewListener() {
            @Override
            public void onLrcSeeked(int newPosition, LrcRow row) {
                application.setSeekTo((int) row.time);
            }
        });
        if(!application.isPause()){
            binding.imgUp.setImageResource(android.R.drawable.ic_media_pause);
        }else {
            binding.imgUp.setImageResource(android.R.drawable.ic_media_play);
        }
        binding.imgBack.setOnClickListener(v -> {Navigation.findNavController(v).popBackStack();});
        ((MainActivity) requireActivity()).goneAll();
        binding.imgIn.setOnClickListener(v-> application.setPn(application.getPn()-1));
        binding.imgUp.setOnClickListener(v-> application.pauseStart());
        binding.imgOut.setOnClickListener(v-> application.setPn(application.getPn()+1));
        binding.sbSpeed255.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                application.setSeekTo((int) (progress));
            }
        });
        return binding.getRoot();
    }


    /**
     * 开始播放歌曲并同步展示歌词
     */
    public void beginLrcPlay(DataMusic data){
        application.addDataMusics(data, new App.MusicEvent() {
            @Override
            public void onCompletion(String lrc) {
                DefaultLrcBuilder builder = new DefaultLrcBuilder();
                List<LrcRow> lrcRows = builder.getLrcRows(lrc);
                binding.lrcView.setLrc(lrcRows);
                time = lrcRows.get(lrcRows.size() - 1).time;
                binding.sbSpeed255.setMax((int) time);
                binding.total.setText(sdr.format(time));
            }

            @Override
            public void onCurrent(DataMusic dataMusic) {

            }

            @Override
            public void onStateChange(Boolean bool) {
                if(bool){
                    binding.imgUp.setImageResource(android.R.drawable.ic_media_pause);
                }else {
                    binding.imgUp.setImageResource(android.R.drawable.ic_media_play);
                }
            }

            @Override
            public void onNull() {

            }

            @Override
            public void onData(List<DataMusic> dataMusics, int i) {

            }
        });
        if(mTimer == null){
            mTimer = new Timer();
            mTask = new LrcTask();
            mTimer.scheduleAtFixedRate(mTask, 0, mPalyTimerDuration);
        }
    }

    /**
     * 停止展示歌曲
     */
    public void stopLrcPlay(){
        if(mTimer != null){
            mTimer.cancel();
            mTimer = null;
        }
    }
    /**
     * 展示歌曲的定时任务
     */
    class LrcTask extends TimerTask{
        @Override
        public void run() {
            try {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        long currentPosition = application.getCurrentPosition();
                        binding.lrcView.seekLrcToTime(currentPosition);
                        binding.totalIng.setText(sdr.format(new Date(currentPosition)));
                        binding.sbSpeed255.setProgress((int) (currentPosition));
                    }
                });
            }catch (NullPointerException e){
                e.printStackTrace();
            }
        }
    };
}